package com.itzhigui.service.impl;

import com.itzhigui.entity.Student;
import com.itzhigui.mapper.StudentMapper;
import com.itzhigui.service.StudentService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author java1412
 * @since 2024-04-12 09:45:15
 */
@Service
@Transactional
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    // 查询出来的所有的学生信息放进redis缓存中
    @Override
    @Cacheable(value = "users")
    public List<Student> findAll() {
        return studentMapper.findAll();
    }

    @Override
    @Cacheable(value = "user", key = "#id", unless = "#result eq null")
    public Student findById(Integer id) {
        return studentMapper.findById(id);
    }

    @Override
    @CachePut(value = "user", key = "#result.id", unless = "#result eq null")
    public Student add(Student student) {
        studentMapper.add(student);
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", 200);
//        map.put("msg", "添加学生信息成功");
//        return map;
        return studentMapper.findById(student.getId());
    }

    @Override
    @CachePut(value = "user", key = "#result.id", unless = "#result eq null")
    public Student update(Student student) {
        studentMapper.update(student);
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", 200);
//        map.put("msg", "更新学生信息成功");
//        return map;
        return studentMapper.findById(student.getId());
    }

    @Override
    @CacheEvict(value = "user", key = "#id")
    public Map<String, Object> deleteById(Integer id) {
        studentMapper.deleteById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "删除学生信息成功");
        return map;
    }
}
